var form;
var layer;
//页面初始化时加载Layui框架
layui.use(['form', 'layer', 'laydate'], function () {
    form = layui.form();
    layer = layui.layer;

    initCompany();
    initRole();

    var companyIdtemp = $("#companyIdtemp").val();
    if (companyIdtemp != -1 && companyIdtemp != "") {
        initGroup(companyIdtemp);
    } else {
        $("#groupId").attr("disabled", true);
        $("#groupId").css("background-color", "gray");
    }

    form.on('select(changeCompany)', function () {
        var companyId = $("#companyId").val();
        $("#companyIdtemp").val(companyId);
        if (companyId != -1 && companyId != "") {
            $("#groupId").attr("disabled", false);
            $("#groupId").css("background-color", "");
            initGroup(companyId);
        } else {
            $("#groupId").empty();
            $("#groupId").append("<option value=''>请选择部门</option>");
            $("#groupId").attr("disabled", true);
            $("#groupId").css("background-color", "gray");
        }
        form.render();
    });

    //加载性别
    var sexTemp = $("#sexTemp").val();
    if (sexTemp != null && sexTemp != "" && sexTemp != undefined) {
        $("input[name='sex'][value=" + sexTemp + "]").attr("checked", true);
        form.render();
    }

    //关闭
    var closed = $(".close");
    closed.click(function () {
        var index = parent.layer.getFrameIndex(window.name); //先得到当前iframe层的索引
        parent.layer.close(index); //再执行关闭
    });
    //监听提交
    form.on('submit(submit)', function () {
        //提交按钮置为不可用
        $("#submit").addClass("layui-btn-disabled");
        addOrUpdateUser();
    });
});

/**
 * 初始化公司
 */
function initCompany() {
    var companyIdtemp = $("#companyIdtemp").val();
    $.ajax({
        url: basePath + "company/getAllCompany.action",
        type: "post",
        dataType: "text",
        success: function (data) {
            var jsonData = eval("(" + data + ")");
            $("#companyId").empty();
            $("#companyId").append("<option value=''>请选择公司</option>");
            if (jsonData.length > 0) {
                for (var i = 0; i < jsonData.length; i++) {
                    if (companyIdtemp == jsonData[i].id) {
                        $("#companyId").append("<option selected value='" + jsonData[i].id + "'>" + jsonData[i].name + "</option>");
                    } else {
                        $("#companyId").append("<option value='" + jsonData[i].id + "'>" + jsonData[i].name + "</option>");
                    }
                }
            }
            form.render();
        }
    });
}

/**
 * 初始化部门
 */
function initGroup(companyId) {
    var groupIdtemp = $("#groupIdtemp").val();
    $.ajax({
        url: basePath + "group/getAllGroup.action?companyId=" + companyId,
        type: "post",
        dataType: "text",
        data: companyId,
        success: function (data) {
            var jsonData = eval("(" + data + ")");
            $("#groupId").empty();
            $("#groupId").append("<option value=''>请选择部门</option>");
            if (jsonData.length > 0) {
                for (var i = 0; i < jsonData.length; i++) {
                    if (groupIdtemp == jsonData[i].id) {
                        $("#groupId").append("<option selected value='" + jsonData[i].id + "'>" + jsonData[i].groupName + "</option>");
                    } else {
                        $("#groupId").append("<option value='" + jsonData[i].id + "'>" + jsonData[i].groupName + "</option>");
                    }
                }
            }
            form.render();
        }
    });
}

/**
 * 初始化角色
 */
function initRole() {
    var roleIdtemp = $("#roleIdtemp").val();
    var paramData = {
        "query": "opera"
    };
    $.ajax({
        url: basePath + "role/findAllRole.action",
        type: "post",
        dataType: "text",
        data: paramData,
        success: function (data) {
            var jsonData = eval("(" + data + ")");
            $("#roleId").empty();
            $("#roleId").append("<option value=''>请选择角色</option>");
            if (jsonData.length > 0) {
                for (var i = 0; i < jsonData.length; i++) {
                    if (roleIdtemp == jsonData[i].id) {
                        $("#roleId").append("<option selected value='" + jsonData[i].id + "'>" + jsonData[i].roleName + "</option>");
                    } else {
                        $("#roleId").append("<option value='" + jsonData[i].id + "'>" + jsonData[i].roleName + "</option>");
                    }
                }
            }
            form.render();
        }
    });
}

/**
 * 验证手机号唯一性
 */
function validatePhone() {
    var userId = $.trim($("#userId").val());
    // 手机
    var cellphone = $.trim($("#cellphone").val());
    var paramData = {
        "user.id": userId,
        "user.cellphone": cellphone
    };
    var urlStr = basePath + "user/validatePhone.action";
    $.ajax({
        url: urlStr,
        type: "post",
        dataType: 'text',
        data: paramData,
        success: function (data) {
            if (data != null && data != "" && data == 1) {
                layer.open({
                    title: '提示',
                    icon: 0,
                    content: '手机号码已存在!',
                    yes: function (index) {
                        $("#cellphone").focus();
                        layer.close(index);
                    }
                });
                return false;
            }
        }
    });
}

/**
 * 新增/修改
 */
function addOrUpdateUser() {
    var userId = $.trim($("#userId").val());
    // 用户名
    var userName = $.trim($("#userName").val());
    // 登录名
    var loginName = $.trim($("#loginName").val());
    // 登录密码
    var loginPass = $.trim($("#newPass").val());
    // 确认密码
    var queryPass = $.trim($("#queryPass").val());
    // 手机
    var cellphone = $.trim($("#cellphone").val());
    // 电话
    var telephone = $.trim($("#telephone").val());
    // 性别
    var sex = $("input[name='sex']:checked").val();
    // 年龄
    var age = $.trim($("#age").val());
    // 邮箱
    var email = $.trim($("#email").val());
    // 所属公司ID
    var companyId = $.trim($("#companyId").val());
    // 所属部门ID
    var groupId = $.trim($("#groupId").val());
    // 所属角色ID
    var roleId = $.trim($("#roleId").val());

    var type = $("#type").val();
    if (null == type || '' == type) {
        type = 'add';
    }

    var paramData = {
        "user.id": userId,
        "user.userName": userName,
        "user.loginName": loginName,
        "user.loginPass": loginPass,
        "user.cellphone": cellphone,
        "user.telephone": telephone,
        "user.sex": sex,
        "user.age": age,
        "user.email": email,
        "user.groupId": groupId,
        "user.roleId": roleId,
        "companyId": companyId,
        "type": type
    };
    $.ajax({
        type: 'post',
        url: basePath + "user/saveUser.action",
        data: paramData,
        dataType: 'text',
        success: function (data) {
            if (data != null && data != "" && data == "success") {
                closeAndRefresh();
            } else if (data == "exist") {
                layer.open({
                    title: '提示',
                    icon: 0,
                    content: '登录名已存在!'
                });
            } else if (data == "comexist") {
                layer.open({
                    title: '提示',
                    icon: 0,
                    content: '所选公司不存在!'
                });
            } else if (data == "groupexist") {
                layer.open({
                    title: '提示',
                    icon: 0,
                    content: '所选部门不存在!'
                });
            } else if (data == "roleexist") {
                layer.open({
                    title: '提示',
                    icon: 0,
                    content: '所选角色不存在!'
                });
            } else {
                var content = '';
                if (type == "add") {
                    content = '新增失败!';
                } else {
                    content = '修改失败!';
                }
                layer.open({
                    title: '错误',
                    icon: 5,
                    content: content,
                    yes: function () {
                        closeAndRefresh();
                    }
                });
            }
            //提交按钮置为可用
            $("#submit").removeClass("layui-btn-disabled");
        }
    });
}